#include <QDebug>
#include "serialconnection.h"
#include <QFile>
#include <QDir>
#include <QMessageBox>
serialConnection::serialConnection()
{
    serPort = new QSerialPort(this);

    initLink();

    connect(serPort, SIGNAL(error(QSerialPort::SerialPortError)), this,
            SLOT(handleError(QSerialPort::SerialPortError)));
//    connect(serPort, SIGNAL(readyRead()), this, SLOT(readData()));
}

serialConnection::~serialConnection()
{
    serPort->close();
}

QString serialConnection::findserial()
{
    int i=0;
    QFile *ser;

    errno = -1;

    for(i=0;i<5;i++)
    {
        ser = new QFile("/dev/ttySAC" + QString::number(i));

        if(ser->exists()) break;

        delete ser;
        ser = NULL;
    }

    if(ser == NULL){

        errno = 0;
        qDebug()<<"ser"<<ser;
        qDebug()<<"USB Serial is not found!";
        return "";
    }

    return ser->fileName();
}
//void serialConnection::initLink()
//{
////    QString str;
//    QString portName;
//    //serial = new QSerialPort(this);
//    if ((portName = findserial()) != "")
//    {
//        qDebug()<<portName;

//        serPort->setPortName(portName);
//        serPort->setBaudRate(QSerialPort::Baud9600);
//        serPort->setDataBits(QSerialPort::Data8);
//        serPort->setParity(QSerialPort::NoParity);
//        serPort->setStopBits(QSerialPort::OneStop);
//        serPort->setFlowControl(QSerialPort::NoFlowControl);
//        serPort->open(QIODevice::ReadWrite);
//    }

//    if (! serPort->open(QIODevice::ReadWrite)) {
//        qDebug()<<"连接串口失败:"+serPort->errorString();
//    }

//}
void serialConnection::initLink()
{

#ifndef i386
    QString devName = "/dev/ttySAC2";
#else
//    QString devName = "/dev/pts/3";
    QString devName = "/dev/ttyUSB0";
#endif

    serPort->setPortName(devName);
    serPort->setBaudRate(9600);
    serPort->setDataBits(QSerialPort::Data8);
    serPort->setParity(QSerialPort::NoParity);
    serPort->setStopBits(QSerialPort::OneStop);
    serPort->setFlowControl(QSerialPort::NoFlowControl);

    if (! serPort->open(QIODevice::ReadWrite)) {

        qDebug()<<"连接串口失败:"+serPort->errorString();
    }
}

void serialConnection::readData()
{
    QByteArray data = serPort->readAll();

    qDebug()<<"we recvd: "<<data.toHex();
}

void serialConnection::handleError(QSerialPort::SerialPortError error)
{
    if(error == QSerialPort::ResourceError) {
        qDebug()<<"连接串口失败:"+serPort->errorString();
    }
}
